package com.bandit.controller;


import com.alibaba.fastjson.JSONObject;
import com.bandit.pojo.Blog;
import com.bandit.pojo.BlogType;
import com.bandit.service.BlogService;
import com.bandit.service.BlogTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

import java.util.*;


@Controller
public class BlogController {

    @Autowired
    private BlogTypeService blogTypeService;

    @Autowired
    private BlogService blogService;

    //去后端
    @RequestMapping("/toBackIndex")
    public ModelAndView toBackIndex(ModelAndView mv){
        mv.setViewName("/back/indexback");
        return mv;
    }

    //博客管理列表页面
    @RequestMapping("/toBlogManger")
    public ModelAndView toBlogManger(ModelAndView mv){
        mv.setViewName("/back/blogManger");
        return mv;
    }

    //博客类型列表页面
    @RequestMapping("/toTypeManger")
    public ModelAndView toTypeManger(ModelAndView mv){
        mv.setViewName("/back/typeManger");
        return mv;
    }

    //评论管理
    @RequestMapping("/toCommentManger")
    public ModelAndView toCommentManger(ModelAndView mv){
        mv.setViewName("/back/commentManger");
        return mv;
    }

    //博客新增
    @RequestMapping("/toBlogAdd")
    public ModelAndView toBlogAdd(ModelAndView mv){
        mv.setViewName("/back/blogAdd");
        return mv;
    }


    //通过id获取类型名称
    @RequestMapping("/getTypeById")
    @ResponseBody
    public String blogTypeById(@RequestParam("id") int id){
        String blogType = blogTypeService.getTypeNameById(id);
        return blogType;
    }

    //通过id获取类型对象
    @RequestMapping("/getBlogTypeById")
    @ResponseBody
    public Map<String,Object> getBlogTypeById(@RequestParam("id") int id){
        BlogType blogType = blogTypeService.getBlogTypeById(id);
        ArrayList<BlogType> blogTypes = new ArrayList<>();
        blogTypes.add(blogType);
        HashMap<String, Object> map = new HashMap<>();
        map.put("blogType",blogTypes);
        HashMap<String, Object> FinaMap = new HashMap<>();
        FinaMap.put("data",blogTypes);
        FinaMap.put("code",0);
        FinaMap.put("count",1);
        return FinaMap;
    }

    //获取类型列表跳转到type
    @RequestMapping("/toType")
    public ModelAndView toType(ModelAndView mv,@RequestParam("id") int id){
        String typeName = blogTypeService.getTypeNameById(id);
        List<Blog> blogList = blogService.getBlogByTypeId(id);
        mv.addObject("blogList",blogList);
        mv.addObject("typeName",typeName);
        mv.setViewName("type");
        return mv;
    }

    //获取类型列表
    @RequestMapping("/queryBlogType")
    @ResponseBody
    public Map<String,Object> queryByType(ModelAndView mv){
        List<BlogType> typeList = blogTypeService.getTypeList();
        HashMap<String, Object> map = new HashMap<>();
        map.put("typeList",typeList);
        return map;
    }

    //获取博客列表
    @GetMapping("/queryBlogList")
    @ResponseBody
    public Map<String,Object> getBlogList(){
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, Object> FinaMap = new HashMap<>();
        List<Blog> allBlog = blogService.getAllBlog();
        map.put("blogList",allBlog);
        FinaMap.put("data",allBlog);
        FinaMap.put("code",0);
        FinaMap.put("count",blogService.selectCount());
        return FinaMap;
    }

    //获取类型列表返回给管理页面
    @GetMapping("/queryTypeList")
    @ResponseBody
    public Map<String,Object> getTypeList(){
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, Object> FinaMap = new HashMap<>();
        List<BlogType> typeList = blogTypeService.getTypeList();
        FinaMap.put("typeList",typeList);
        FinaMap.put("data",typeList);
        FinaMap.put("code",0);
        FinaMap.put("count",blogTypeService.selectCount());
        return FinaMap;
    }


    //ID获取博客
    @GetMapping("/getBlogByID")
    @ResponseBody
    public Map<String,Object> getBlogByID(@RequestParam("id")int id){
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, Object> FinaMap = new HashMap<>();
        Blog blog = blogService.getBlogById(id);
        List<Blog> blogs = new ArrayList<>();
        blogs.add(blog);
        map.put("blogList",blogs);
        FinaMap.put("data",blogs);
        FinaMap.put("code",0);
        FinaMap.put("count",1);
        return FinaMap;
    }

    //editor处理图片上传
    @RequestMapping("/editormdPic")
    @ResponseBody
    public JSONObject editormdPic (@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws Exception{

        String trueFileName = file.getOriginalFilename();

        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));

        String fileName = System.currentTimeMillis()+"_"+ new Random().nextLong() +suffix;

        String path = request.getSession().getServletContext().getRealPath("/assets/msg/upload/");
        System.out.println(path);

        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }


        JSONObject res = new JSONObject();
        res.put("url", "/assets/msg/upload/"+fileName);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;

    }

    //添加博客
    @RequestMapping("/AddBlog")
    @ResponseBody
    public Map<String,Object> BlogAdd(@RequestParam("title") String title,
                                      @RequestParam("summary") String summary,
                                      @RequestParam("keyword") String keyword,
                                      @RequestParam("content") String content,
                                      @RequestParam("blogTypeId") int blogTypeId,
                                      @RequestParam("test-editor-html-code") String HtmlContent){
        int id = blogService.getLastBlogId();
        System.out.println("现在的id"+id);
        System.out.println("类型id"+blogTypeId);
        content = "\n"+content; //在editormd解析Markdown为HTML时不加 换行 会解析出错
        Blog blog = new Blog(id+1, title, summary, content, keyword, blogTypeId);
        blogService.insertBlog(blog);
        System.out.println("title:"+title);
        System.out.println("summary:"+summary);
        HashMap<String, Object> map = new HashMap<>();
        map.put("status","ok");
        return map;
    }

    //添加类型
    @RequestMapping("/AddType")
    @ResponseBody
    public Map<String,Object> TypeAdd(@RequestParam("id") int id,
                                      @RequestParam("typeName") String typeName,
                                      @RequestParam("orderNum") int orderNum){
        BlogType blogType = new BlogType(id, typeName, orderNum);
        blogTypeService.insertBlogType(blogType);
        HashMap<String, Object> map = new HashMap<>();
        map.put("status","ok");
        return map;
    }

    //删除博客
    @RequestMapping("/DeleteBlog")
    @ResponseBody
    public String BlogDelete(@RequestParam("id") int id){
        blogService.deleteBlogById(id);
        return "ok";
    }

    //跳转到博客修改携带通过ID查询的值
    @RequestMapping("/toUpdateBlog")
    public ModelAndView toUpdate(ModelAndView mv,@RequestParam("id")int id){
        Blog blogById = blogService.getBlogById(id);
        mv.addObject("blog",blogById);
        mv.setViewName("/back/blogEdit");
        return mv;
    }

    //博客修改
    @RequestMapping("/UpdateBlog")
    @ResponseBody
    public Map<String,Object> UpdateBlog(@RequestParam("id") int id,
                                         @RequestParam("title") String title,
                                         @RequestParam("summary") String summary,
                                         @RequestParam("keyword") String keyword,
                                         @RequestParam("content") String content,
                                         @RequestParam("blogTypeId") int blogTypeId,
                                         @RequestParam("test-editor-html-code") String HtmlContent){

        content = "\n"+content;
        Blog blog = new Blog(id, title, summary, content, keyword, blogTypeId);
        blogService.updateBlog(blog);
        System.out.println("title:"+title);
        System.out.println("summary:"+summary);
        System.out.println("content:"+content);
        System.out.println("HtmlContent:"+HtmlContent);
        HashMap<String, Object> map = new HashMap<>();
        map.put("status","ok");
        return map;
    }
    //更新类型
    @RequestMapping("/UpdateType")
    @ResponseBody
    public Map<String,Object> UpdateType(@RequestParam("id") int id,
                                         @RequestParam("typeName") String typeName,
                                         @RequestParam("orderNum") int orderNum){
        BlogType blogType = new BlogType(id, typeName, orderNum);
        blogTypeService.updateBlogType(blogType);
        HashMap<String, Object> map = new HashMap<>();
        map.put("status","ok");
        return map;
    }




}
